<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="状态" prop="applyStatus">
        <dict-select :options="dict.type.audit_type" v-model="queryParams.applyStatus" placeholder="请选择审核状态"/>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          type="primary"-->
    <!--          plain-->
    <!--          icon="el-icon-plus"-->
    <!--          size="mini"-->
    <!--          @click="handleAdd"-->
    <!--          v-hasPermi="['car:anchor:add']"-->
    <!--        >新增</el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->

    <el-table v-loading="loading" :data="anchorList">
      <el-table-column label="用户名" align="left" prop="userName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="用户ID" align="left" prop="userRandomId" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="主播信息" align="left" prop="anchorName" width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div>姓名：{{ scope.row.anchorName }}</div>
          <div>电话：{{ scope.row.phone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="粉丝数量" align="center" prop="fansNumber" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="直播总销量" align="center" prop="salesVolume" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="直播总销售金额" align="center" prop="salesQuota" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ $yun.priceFormatter(scope.row.salesQuota) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单总数量" align="center" prop="orderNumber" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="冻结" align="center" prop="anchorStatus" width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.anchorStatus" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                     :inactive-value="0" @change="disableChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="允许直播/不允许" align="center" prop="applyStatus" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.liveEntertainment"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChange1(scope.row.id)"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="任务" align="center" prop="taskAuthority" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.taskAuthority"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChange(scope.row.id)"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
<!--      <el-table-column label="审批状态" align="center" prop="applyStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_type" :value="scope.row.applyStatus"/>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="410" fixed="right">
        <template slot-scope="scope">
          <div style="display: flex;flex-wrap: wrap">
            <block v-if="scope.row.applyStatus === 2">
              <el-button size="mini" type="text" @click="hadndNew(1,scope.row)">结算方式设定</el-button>
              <el-button size="mini" type="text" @click="hadndNew(2,scope.row)">时长和底薪设定</el-button>
              <el-button size="mini" type="text" @click="hadndNew(3,scope.row)">带货提成设定</el-button>
              <el-button size="mini" type="text" @click="hadndNew(4,scope.row)">礼物提成设定</el-button>
<!--              <el-button size="mini" type="text" @click="hadndNew(5,scope.row)">任务设定</el-button>-->
              <el-button size="mini" type="text" @click="$router.push(`/live/liveAudit?name=${scope.row.anchorName}`)">直播记录</el-button>
            </block>
            <el-button size="mini" type="text" @click="handleDetails(scope.row)">查看主播信息</el-button>

            <div class="audit-group" v-if="scope.row.applyStatus == 0">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="handleAudit(scope.row,1)"
                v-hasPermi="['car:anchor:remove']"
              >通过
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-close"
                @click="handleAudit(scope.row,2)"
                v-hasPermi="['car:anchor:remove']"
              >拒绝
              </el-button>
            </div>
            <div class="audit-group" v-else>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['car:anchor:remove']"
              >删除
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改主播对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主播名字" prop="anchorName">
          <el-input v-model="form.anchorName" placeholder="请输入主播名字"/>
        </el-form-item>
        <el-form-item label="销售额" prop="salesQuota">
          <el-input v-model="form.salesQuota" placeholder="请输入销售额"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    主播详情对话框-->
    <el-dialog title="主播详情信息" :visible.sync="openDetails" width="800px" append-to-body>

      <el-descriptions class="margin-top" title="" :column="3" size="medium" border>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            姓名
          </template>
          {{ detailsObj.anchorName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            联系方式
          </template>
          {{ detailsObj.phone }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            主播状态
          </template>
          <dict-tag :options="dict.type.anchor_status" :value="detailsObj.anchorStatus"/>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            审批状态
          </template>
          <dict-tag :options="dict.type.audit_type" :value="detailsObj.applyStatus"/>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-office-building"></i>
            粉丝数量
          </template>
          {{ detailsObj.fansNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-goblet-full"></i>
            销量
          </template>
          {{ detailsObj.salesVolume }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-goblet-square"></i>
            销售额
          </template>
          {{ $yun.priceFormatter(detailsObj.salesQuota) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            创建人
          </template>
          {{ detailsObj.createBy }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-c-scale-to-original"></i>
            创建时间
          </template>
          {{  $yun.convertTimestamp(detailsObj.createTime)}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            更新人
          </template>
          {{ detailsObj.updateBy }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-pie-chart"></i>
            更新时间
          </template>
          {{ $yun.convertTimestamp(detailsObj.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>

<!--      <div class="detials-group">
        <el-row>
          <el-col :span="6">姓名</el-col>
          <el-col :span="18">{{ detailsObj.anchorName }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">联系方式</el-col>
          <el-col :span="18">{{ detailsObj.phone }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">主播状态</el-col>
          <el-col :span="18">
            <dict-tag :options="dict.type.anchor_status" :value="detailsObj.anchorStatus"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">审批状态</el-col>
          <el-col :span="18">
            <dict-tag :options="dict.type.audit_type" :value="detailsObj.applyStatus"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">粉丝数量</el-col>
          <el-col :span="18">{{ detailsObj.fansNumber }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">销量</el-col>
          <el-col :span="18">{{ detailsObj.salesVolume }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">销售额</el-col>
          <el-col :span="18">{{ $yun.priceFormatter(detailsObj.salesQuota) }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">创建人</el-col>
          <el-col :span="18">{{ detailsObj.createBy }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">创建时间</el-col>
          <el-col :span="18">{{ detailsObj.createTime }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">更新人</el-col>
          <el-col :span="18">{{ detailsObj.updateBy }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6">更新时间</el-col>
          <el-col :span="18">{{ detailsObj.updateTime }}</el-col>
        </el-row>
      </div>-->

    </el-dialog>

    <!--    弹窗组-->
    <el-dialog :title="title" :visible.sync="open1" width="500px" append-to-body @close="newForm = {}">
      <el-radio v-model="newForm.clearingForm" :label="1">底薪</el-radio>
      <el-radio v-model="newForm.clearingForm" :label="2">提成</el-radio>
      <el-radio v-model="newForm.clearingForm" :label="3">底薪加提成</el-radio>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNew">确 定</el-button>
        <el-button @click="open1 = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open2" width="500px" append-to-body
               @close="newForm = {};$refs['formNew1'].clearValidate()"
    >
      <el-form ref="formNew1" :model="newForm" label-width="80px">
        <el-form-item label="直播时长" prop="shichang" :rules="[{required: true,message: '直播时长不能为空',trigger: 'blur'}]">
          <el-input v-model="newForm.shichang" placeholder="多个直播时间段以逗号隔开"/>
        </el-form-item>
        <el-form-item label="直播底薪" prop="dixin" :rules="[{required: true,message: '直播底薪不能为空',trigger: 'blur'}]">
          <el-input v-model="newForm.dixin" placeholder="主播直播底薪/月(单位:元)"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNew">确 定</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open3" width="500px" append-to-body
               @close="newForm = {};$refs['formNew1'].clearValidate()"
    >
      <el-form ref="formNew1" :model="newForm" label-width="130px">
        <el-form-item label="主播带货提成" prop="commissionRate" :rules="[{required: true,message: '主播带货提成不能为空',trigger: 'blur'}]">
          <percentage :controls="true" :num.sync="newForm.commissionRate"></percentage>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNew">确 定</el-button>
        <el-button @click="open3 = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open4" width="500px" append-to-body
               @close="newForm = {};$refs['formNew1'].clearValidate()"
    >
      <el-form ref="formNew1" :model="newForm" label-width="130px">
        <el-form-item label="主播礼物提成" prop="giftRatio" :rules="[{required: true,message: '主播礼物提成不能为空',trigger: 'blur'}]">
          <percentage :controls="true" :num.sync="newForm.giftRatio"></percentage>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNew">确 定</el-button>
        <el-button @click="open4 = false">取 消</el-button>
      </div>
    </el-dialog>

<!--    <el-dialog :title="title" :visible.sync="open5" width="500px"
               @close="newForm = {};$refs['formNew1'].clearValidate()"
    >
      <el-form ref="formNew1" :model="newForm" label-width="130px">
        <el-form-item label="开关按钮" prop="giftRatio">
          <el-switch
          v-model="newForm.value"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="switchChange(newForm.id)">
        </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNew">确 定</el-button>
        <el-button @click="open5 = false">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import {
  listAnchor,
  getAnchor,
  delAnchor,
  addAnchor,
  updateAnchor,
  anchorAudit,
  anchorStatusChange,
  settlementAllocation,
  taskAuthority, liveEntertainment
} from '@/api/live/anchorList'

export default {
  name: 'Anchor',
  components: {},
  dicts: ['audit_type', 'anchor_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主播表格数据
      anchorList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      open3: false,
      open4: false,
      open5: false,
      open6: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: '用户id不能为空', trigger: 'blur' }
        ],
        fansNumber: [
          { required: true, message: '粉丝数量不能为空', trigger: 'blur' }
        ],
        salesVolume: [
          { required: true, message: '销量不能为空', trigger: 'blur' }
        ],
        salesQuota: [
          { required: true, message: '销售额不能为空', trigger: 'blur' }
        ],
        order: [
          { required: true, message: '订单数不能为空', trigger: 'blur' }
        ],
        anchorStatus: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        applyStatus: [
          { required: true, message: '申请审批状态不能为空', trigger: 'change' }
        ],
        delete: [
          { required: true, message: '是否删除不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: true, message: '更新时间不能为空', trigger: 'blur' }
        ]
      },
      rules1: {
        shichang: [
          { required: true, message: '时长不能为空', trigger: 'blur' }
        ],
        dixin: [
          { required: true, message: '底薪不能为空', trigger: 'blur' }
        ]
      },
      detailsObj: {},
      openDetails: false,
      typeNew: null,
      newForm: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询主播列表 */
    getList() {
      this.loading = true
      listAnchor(this.queryParams).then(response => {
        this.anchorList = response.data.records
        this.anchorList.forEach(item=>{
          item.commissionRate = item.commissionRate * 100;
          item.giftRatio = item.giftRatio * 100
          if(item.basicSalary != null){
            let str = item.basicSalary;
            let obj = JSON.parse(str);
            let result = {};
            for (let key in obj) {
              let newKey = String(key);
              result[newKey] = String(obj[key]);
            }
            let str1 = '';
            let str2 = '';
            for (let key in result) {
              if (result.hasOwnProperty(key)) {
                str1+=key+','
                str2+=result[key]+','
              }
            }
            str1 = str1.slice(0, -1);
            str2 = str2.slice(0, -1);
            this.$set(item,'shichang',str1)
            this.$set(item,'dixin',str2)
          }
        })
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        anchorName: null,
        fansNumber: null,
        salesVolume: null,
        salesQuota: null,
        order: null,
        phone: null,
        anchorStatus: null,
        applyStatus: null,
        delete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新加的操作
    hadndNew(type, row) {
      this.typeNew = type
      this.newForm = JSON.parse(JSON.stringify(row))
      console.log('this.newForm',this.newForm)
      if (type === 1) {
        this.open1 = true
        this.title = '结算方式设定'
      }
      if (type === 2) {
        this.open2 = true
        this.title = '时长和底薪设定'
      }
      if (type === 3) {
        this.open3 = true
        this.title = '带货提成设定'
      }
      if (type === 4) {
        this.open4 = true
        this.title = '礼物提成设定'
      }
      if (type === 5) {
        this.open5 = true
        this.title = '任务设定'
      }
      if (type === 6) {
        this.open6 = true
        this.title = '查看直播记录'
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加主播'
    },
    /** 修改按钮操作 */
    handleDetails(row) {
      const id = row.id || this.ids
      getAnchor(id).then(response => {
        this.detailsObj = response.data
        this.openDetails = true

      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAnchor(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addAnchor(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    switchChange(id){
      taskAuthority(id).then(res => {
        this.getList()
        this.$modal.msgSuccess('修改成功')
      })
    },
    switchChange1(id){
      liveEntertainment(id).then(res => {
        this.getList()
        this.$modal.msgSuccess('修改成功')
      })
    },
    submitFormNew() {
      let cloneForm = JSON.parse(JSON.stringify(this.newForm))
      if (this.typeNew === 2) {
        var result = this.strTurnKeyVal(cloneForm.shichang,cloneForm.dixin);
        if(result === undefined) return
        cloneForm.basicSalary = JSON.stringify(result)
      }
      cloneForm.commissionRate = cloneForm.commissionRate / 100
      cloneForm.giftRatio = cloneForm.giftRatio / 100
      if(cloneForm.commissionRate === 0) cloneForm.commissionRate = null
      if(cloneForm.giftRatio === 0) cloneForm.giftRatio = null
      settlementAllocation(cloneForm).then(res => {
        if(!res.success) return
        if (this.typeNew === 1) this.open1 = false
        if (this.typeNew === 2) this.open2 = false
        if (this.typeNew === 3) this.open3 = false
        if (this.typeNew === 4) this.open4 = false
        if (this.typeNew === 5) this.open5 = false
        if (this.typeNew === 6) this.open6 = false
        this.getList()
        this.this.newForm = {}
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除主播编号为"' + ids + '"的数据项？').then(function() {
        return delAnchor([ids])
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      anchorStatusChange('car/anchor/export', {
        ...this.queryParams
      }, `anchor_${new Date().getTime()}.xlsx`)
    },
    /** 身份冻结修改 */
    disableChange(row) {
      anchorStatusChange(row.id).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.getList()
      })
    },
    /** 审核 */
    handleAudit(row, status) {
      this.$modal.confirm('是否确认执行审核？').then(function() {
        return anchorAudit({ userId: row.userId, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('审核成功！')
      }).catch(() => {
      })
      /* anchorAudit({userId:row.userId,status:status}).then(response=>{
        this.$modal.msgSuccess(response.msg);
        this.getList();
      }) */
    },
    strTurnKeyVal(str1,str2){
      // 将中文逗号替换为英文逗号
      str1 = str1.replace(/，/g, ',');
      str2 = str2.replace(/，/g, ',');
      // 将两个字符串拆分成数组
      const arr1 = str1.split(',');
      const arr2 = str2.split(',');
      if (arr1.length !== arr2.length) return this.$modal.msgError('键和值的数量不一致')
      // 将两个数组转换为键值对数组
      let str = arr1.map((item, index) => {
        const obj = {};
        obj[item] = arr2[index];
        return obj;
      });
      const obj = str.reduce((acc, cur) => {
        const key = Object.keys(cur)[0];
        const value = cur[key];
        acc[key] = value;
        return acc;
      }, {});
      console.log('obj',obj)
      return obj
    },
  }
}
</script>
<style lang="scss" scoped>
.detials-group {
  line-height: 40px;
  font-size: 16px;
  padding-left: 20px;
}
</style>
